<template>
  <view style="background: linear-gradient(to bottom, #f8f8f8, #f9eff7, #f8f8f8)">
    <view class="g-bg" :style="{ height: windowHeight }">
      <view class="g-polygon g-polygon-1"></view>
      <view class="g-polygon g-polygon-2"></view>
      <view class="g-polygon g-polygon-3"></view>
    </view>
    <view style="position: absolute; top: 0; left: 0; z-index: 2; width: 100vw; height: 100vh; overflow: hidden" :style="{ height: windowHeight }">
      <view class="step-box" :class="isNext ? 'next' : 'init'" :style="{ height: windowHeight }">
        <view class="step step1" :style="{ transitionDuration }">
          <view style="display: flex; flex-direction: column; margin-top: 20px">
            <text style="font-size: 32px; font-weight: bold" :style="{ color: defThemeColor.text }">第1步:获取验证码</text>
            <text style="margin-top: 10px; font-size: 14px" :style="{ color: defThemeColor.text3 }">
              为你您的账户安全,我们需要验证您绑定的手机号以便于我们确认您的身份!
            </text>
          </view>
          <mxp-form
            ref="mxpSmsCodeFormRef"
            :model="smsCodeForm"
            :fromBorderColor="false"
            itemLabelWidth="80px"
            :rules="codeRules"
            :cusStyle="{ width: '690rpx' }"
          >
            <mxp-form-item :borderColor="false" labelWidth="0px" label="" prop="phone" :cusStyle="{ marginBottom: `5px`, marginTop: '20px' }">
              <view style="display: flex; align-items: center; height: 48px; padding: 0 15px; border-radius: 10px" :style="{ background: defThemeColor.fill }">
                <text :style="{ color: defThemeColor.text2 }">{{ phone }}</text>
              </view>
            </mxp-form-item>
            <mxp-form-item :borderColor="false" labelWidth="0px" prop="smsCode" label="">
              <mxp-input
                v-model="smsCodeForm.smsCode"
                placeholder="请输入验证码"
                :cusStyle="{ borderRadius: `10px`, padding: '0px 15px' }"
                :inputStyle="{ height: '48px', padding: '0px 0px' }"
                type="number"
                :maxlength="smsCodeLen"
              >
                <template #suffix>
                  <mxp-count-down-button ref="mxpCountDownButtonRef" :seconds="60" :cusStyle="{ height: '48px' }" @click="sendAuthCode"></mxp-count-down-button>
                </template>
              </mxp-input>
            </mxp-form-item>
          </mxp-form>
          <mxp-button
            text="下 一 步"
            :background="defThemeColor.buttonColor"
            font-size="18px"
            :bold="true"
            :loading="loging"
            :disabled="loging"
            :cusStyle="{ height: '48px', width: '690rpx', maxWidth: '400px', marginTop: '20px' }"
            @click="onNextClick"
          ></mxp-button>
        </view>
        <view class="step step2" :style="{ transitionDuration }">
          <view style="display: flex; flex-direction: column; margin-top: 20px">
            <text style="font-size: 32px; font-weight: bold" :style="{ color: defThemeColor.text }">第2步:修改密码</text>
            <text style="margin-top: 10px; font-size: 14px" :style="{ color: defThemeColor.text3 }">
              密码仅可由数字、英文字母或英文符号组成，且需包含其中 至少两种类型，长度不少于8个字符
            </text>
          </view>
          <mxp-form ref="mxpPassdFormRef" :model="passdForm" :fromBorderColor="false" itemLabelWidth="80px" :rules="passdRules" :cusStyle="{ width: '690rpx' }">
            <mxp-form-item :borderColor="false" labelWidth="0px" label="" prop="password" :cusStyle="{ marginBottom: `5px`, marginTop: '20px' }">
              <mxp-input
                v-model="passdForm.password"
                placeholder="请输入密码"
                :password="true"
                :cusStyle="{ borderRadius: `10px`, padding: '0px 15px' }"
                :inputStyle="{ height: '48px', padding: '0px 0px' }"
                :maxlength="passwordMax"
              ></mxp-input>
            </mxp-form-item>
            <mxp-form-item :borderColor="false" labelWidth="0px" prop="affirmPassword" label="">
              <mxp-input
                v-model="passdForm.affirmPassword"
                placeholder="请再次输入密码"
                :password="true"
                :cusStyle="{ borderRadius: `10px`, padding: '0px 15px' }"
                :inputStyle="{ height: '48px', padding: '0px 0px' }"
                :maxlength="passwordMax"
              ></mxp-input>
            </mxp-form-item>
          </mxp-form>
          <mxp-button
            text="修改密码"
            :background="defThemeColor.buttonColor"
            font-size="18px"
            :bold="true"
            :loading="loging"
            :disabled="loging"
            :cusStyle="{ height: '48px', width: '690rpx', maxWidth: '400px', marginTop: '20px' }"
            @click="onChangePassword"
          ></mxp-button>
          <mxp-button
            text="上 一 步"
            font-size="18px"
            :bold="true"
            :plain="true"
            :cusStyle="{ height: '38px', width: '690rpx', maxWidth: '400px', marginTop: '20px' }"
            @click="() => (isNext = false)"
          ></mxp-button>
        </view>
      </view>
    </view>
    <mxp-toast ref="mxpToastRef" :customNav="true"></mxp-toast>
  </view>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive, ref } from 'vue';
  import MxpInput from '@/mxp-ui/mxp-input/mxp-input.vue';
  import MxpButton from '@/mxp-ui/mxp-button/mxp-button.vue';
  import MxpToast from '@/mxp-ui/mxp-toast/mxp-toast.vue';
  import MxpForm, { type $RuleItem, type $Rules } from '@/mxp-ui/mxp-form/mxp-form.vue';
  import MxpFormItem from '@/mxp-ui/mxp-form-item/mxp-form-item.vue';
  import MxpCountDownButton from '@/mxp-ui/mxp-count-down-button/mxp-count-down-button.vue';
  import { SmsType, changePasswordAxios, sendAuthCodeByUserAxios } from '@/api/account';
  import { useAppStore } from '@/pinia/app';
  import { getPasswordRules, getSmsCodeRules } from '@/utils/page/rules';
  import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
  import { defThemeColor } from '@/mxp-ui/mxp-tool/theme/theme';

  const sys = mxpGetSysInfoStore().getSysInfo();
  const windowHeight = computed(() => `${sys.value.windowHeight}px`);
  const transitionDuration = ref('0s');
  const appStore = useAppStore();
  const mxpSmsCodeFormRef = ref<InstanceType<typeof MxpForm> | null>(null);
  const mxpPassdFormRef = ref<InstanceType<typeof MxpForm> | null>(null);
  const mxpCountDownButtonRef = ref<InstanceType<typeof MxpCountDownButton> | null>(null);
  const mxpToastRef = ref<InstanceType<typeof MxpToast> | null>(null);
  const loging = ref(false);
  const isNext = ref(false);
  const phone = computed(() => appStore.userInfo?.phone || '');
  const { passwordMax, passwordRules } = getPasswordRules();
  const { smsCodeLen, smsCodeRules } = getSmsCodeRules();

  const smsCodeForm = reactive({
    smsCode: '',
  });

  const passdForm = reactive({
    password: '',
    affirmPassword: '',
  });

  onMounted(() => {
    transitionDuration.value = '0.3s';
  });

  const codeRules: $Rules<typeof smsCodeForm> = {
    smsCode: smsCodeRules,
  };

  const passdRules = computed<$Rules>(() => {
    const _rules: $Rules<typeof passdForm> = {
      password: passwordRules('新密码'),
      affirmPassword: passwordRules('确认密码'),
    };
    if (passdForm.password) {
      const regExp = RegExp(`^${passdForm.password}$`);
      const affirmRules: $RuleItem = { pattern: regExp, type: 'string', message: '两次输入密码不一致', trigger: ['blur', 'change'] };
      (_rules.affirmPassword as $RuleItem[]).push(affirmRules);
    }
    return _rules;
  });

  /** 下一步 */
  async function onNextClick() {
    try {
      await mxpSmsCodeFormRef.value!.validate();
      isNext.value = true;
    } catch (error) {}
  }

  /**
   * 发送验证码
   */
  async function sendAuthCode() {
    try {
      await mxpSmsCodeFormRef.value!.validateField('phone');
      mxpCountDownButtonRef.value?.setLoadState(true);
      await sendAuthCodeByUserAxios(SmsType.AppSMSUpdatePassword);
      mxpCountDownButtonRef.value?.setLoadState(false);
      mxpCountDownButtonRef.value?.start(); // 开始倒计时
    } catch (err) {
      mxpCountDownButtonRef.value?.setLoadState(false);
      mxpToastRef.value?.showError(err.msg || '验证码发送失败');
    }
  }

  /**
   * 修改密码
   */
  async function onChangePassword() {
    try {
      await mxpSmsCodeFormRef.value?.validate();
      await mxpPassdFormRef.value?.validate();
      loging.value = true;
      await changePasswordAxios({ smsCode: smsCodeForm.smsCode, password: passdForm.password });
      loging.value = false;
      useAppStore().logOut();
      uni.reLaunch({ url: `/pages/account/login/login` });
    } catch (err) {
      if (err.data === 40006) {
        isNext.value = false;
        smsCodeForm.smsCode = '';
      }
      loging.value = false;
      mxpToastRef.value?.showError(Array.isArray(err) && err[0] && err[0].message ? err[0].message : err.msg || '操作失败,-BD0002');
    }
  }
</script>

<style lang="scss" scoped>
  .step-box {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 750rpx;
    height: 100%;
    overflow: hidden;

    .step {
      position: absolute;
      top: 0;
      left: 0;
      box-sizing: border-box;
      width: 750rpx;
      height: 100%;
      padding: 30rpx;
      overflow: hidden;
      transition: transform 0.3s ease;
    }

    &.init {
      .step1 {
        transform: translateX(0);
      }

      .step2 {
        transform: translateX(100vw);
      }
    }

    &.next {
      .step1 {
        transform: translateX(-100vw);
      }

      .step2 {
        transform: translateX(0);
      }
    }
  }

  .g-bg {
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: hidden;

    .g-polygon {
      position: absolute;
      opacity: 0.5;
    }

    &:before {
      position: absolute;
      inset: 0;
      z-index: 1;
      content: '';
      backdrop-filter: blur(40px);
    }

    .g-polygon-1 {
      top: 150px;
      left: -10%;
      width: 500rpx;
      height: 400rpx;
      clip-path: polygon(0 10%, 30% 0, 100% 40%, 70% 100%, 20% 90%);
      background: linear-gradient(#f2f2c8, #e3eeaf);
      animation: rotate-animation 8s infinite linear;
    }

    .g-polygon-2 {
      top: 150px;
      left: 38%;
      width: 600rpx;
      height: 400rpx;
      clip-path: polygon(10% 0, 100% 70%, 100% 100%, 20% 90%);
      background: linear-gradient(-36deg, #eebab1, #f7cab7);
      animation: rotate-animation 8s infinite linear;
    }

    .g-polygon-3 {
      top: 150px;
      left: 20%;
      width: 500rpx;
      height: 300rpx;
      clip-path: polygon(80% 0, 100% 70%, 100% 100%, 20% 90%);
      background: linear-gradient(0deg, #f5e2b9, #f2dbbb);
      animation: rotate-animation 9s infinite linear;
    }
  }

  @keyframes rotate-animation {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }
</style>
